﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.IO;
using System.ServiceProcess;
using System.Windows.Forms;

namespace ApplicationSentinelManage
{
    public partial class Form1 : Form
    {
        //ApplicationSentinelInstaller installer1;// = new ApplicationSentinelInstaller();
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            this.Text = "应用程序监控服务程序管理";
            //installer1 = new ApplicationSentinelInstaller();
        }
        FileMessage Fmegs;
        private void Btn_ButtonClick(object sender, EventArgs e)
        {
            System.Windows.Forms.Button btn = sender as System.Windows.Forms.Button;
            if (btn != null)
            {
                switch (btn.Name)
                {
                    case "BtnOpen":
                        // 启动服务
                        Fmegs = GetFilePath();
                        if (Fmegs != null)
                        {
                            AppPatch.Text = Fmegs.FileFull;
                            AppPatch.Text +="\r\n"+Fmegs.FilePath;
                            AppPatch.Text += "\r\n" + Fmegs.FileName;
                            BtnInstall.Enabled = BtnStart.Enabled = BtnClose.Enabled = BtnUninstall.Enabled = true;
                        }
                        else
                        {
                            BtnInstall.Enabled = BtnStart.Enabled = BtnClose.Enabled = BtnUninstall.Enabled = true;
                        }
                        break;
                    case "BtnInstall":
                        // 安装服务
                        try
                        {
                            if (IsServiceExisted(Fmegs.FileName)) UninstallService(Fmegs.FileName);
                            InstallService(Fmegs.FileFull);
                            MessageBox.Show("安装服务完成");
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                        break;
                    case "BtnStart":
                        // 启动服务
                        try
                        {
                            if (IsServiceExisted(Fmegs.FileName)) ServiceStart(Fmegs.FileName);
                            MessageBox.Show("启动服务完成");
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                        break;
                    case "BtnClose":
                        // 停止
                        try
                        {
                            if (IsServiceExisted(Fmegs.FileName)) ServiceStop(Fmegs.FileName);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("无法停止服务！" + ex.ToString());
                        }
                        break;
                    case "BtnUninstall":
                        // 卸载服务
                        try
                        {
                            if (IsServiceExisted(Fmegs.FileName))
                            {
                                ServiceStop(Fmegs.FileName);
                                UninstallService(Fmegs.FileFull);
                                MessageBox.Show("卸载服务完成");
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                        break;
                    default:
                        MessageBox.Show("未知操作");
                        break;
                }
            }
            else
            {
                MessageBox.Show("按钮无效");
            }

        }
        private FileMessage GetFilePath()
        {
            FileMessage FM = null;
            try
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Title = "选择一个文件";
                openFileDialog.Filter = "所有文件 (*.*)|*.*";

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    string fullPath = openFileDialog.FileName;
                    string directory = Path.GetDirectoryName(fullPath);
                    string fileName = Path.GetFileName(fullPath).Replace(".exe","");
                    FM = new FileMessage
                    {
                        FileName = fileName,
                        FilePath = directory,
                        FileFull = fullPath
                    };
                    Console.WriteLine("文件路径: " + fullPath);
                    Console.WriteLine("所在目录: " + directory);
                    Console.WriteLine("文件名称: " + fileName);
                    return FM;
                }
                return null; // 如果用户取消了选择，则返回 null
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message + e.InnerException);
                return null;
            }
        }
        #region  //服务管理项

        //判断服务是否存在
        private bool IsServiceExisted(string FileName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController sc in services)
            {
                if (sc.ServiceName.ToLower() == FileName.ToLower())
                {
                    return true;
                }
            }
            Console.WriteLine("未能找到："+Fmegs.FileName+" 相关文件");
            return false;
        }

        //安装服务
        private void InstallService(string FileFull)
        {
            using (AssemblyInstaller installer = new AssemblyInstaller())
            {
                installer.UseNewContext = true;
                installer.Path = FileFull;
                IDictionary savedState = new Hashtable();
                installer.Install(savedState);
                installer.Commit(savedState);
            }
        }

        //卸载服务
        private void UninstallService(string FileFull)
        {
            using (AssemblyInstaller installer = new AssemblyInstaller())
            {
                installer.UseNewContext = true;
                installer.Path = FileFull;
                installer.Uninstall(null);
            }
        }
        //启动服务
        private void ServiceStart(string FileName)
        {
            using (ServiceController control = new ServiceController(FileName))
            {
                if (control.Status == ServiceControllerStatus.Stopped)
                {
                    control.Start();
                }
            }
        }
        //停止服务
        private void ServiceStop(string FileName)
        {
            using (ServiceController control = new ServiceController(FileName))
            {
                if (control.Status == ServiceControllerStatus.Running)
                {
                    control.Stop();
                }
            }
        }
        #endregion






    }

    //[RunInstaller(true)]
    //public class ApplicationSentinelInstaller : Installer
    //{
    //    public ApplicationSentinelInstaller()
    //    {
    //        ServiceProcessInstaller processInstaller = new ServiceProcessInstaller();
    //        ServiceInstaller serviceInstaller = new ServiceInstaller();

    //        // 设置服务运行账户
    //        processInstaller.Account = ServiceAccount.LocalSystem;

    //        // 设置服务信息
    //        serviceInstaller.ServiceName = "ApplicationSentinelService";
    //        serviceInstaller.DisplayName = "Application Sentinel Service";
    //        serviceInstaller.Description = "守护应用的监控服务";
    //        serviceInstaller.StartType = ServiceStartMode.Automatic;

    //        // 添加到 Installers 集合中
    //        Installers.Add(processInstaller);
    //        Installers.Add(serviceInstaller);
    //    }
    //}
    public class FileMessage
    { 
        public string FileName { get; set; }
        public string FilePath { get; set; }
        public string FileFull { get; set; }
    }
}
